import psycopg2
from pprint import pprint
import ConfigParser
conn = None
try:
	config = ConfigParser.RawConfigParser()
	config.read('/etc/ude/switch/database.ini')
	conn = psycopg2.connect("dbname='{0}' user='{1}' host='{2}' password='{3}'".format(config.get('Database','dbname'),config.get('Database','user'),config.get('Database','host'),config.get('Database','password')));
except:
	print "I am unable to connect to the database"


dids = None

if __name__ == "__main__":
	c = conn.cursor()
	c.execute("""SELECT did,ata,line,cid,mailbox,record,ring_seconds FROM t_did;""")
	dids = c.fetchall()
	del c
	
	formatted = "// Generated, do not edit manually.\n"
		
	# How the internal system calls numbers
	formatted += "context internal_gen {\n"
	
	for did in dids:
		did_n = did[0]
		record = did[5]
		ring_sec = did[6]
		mailbox = did[4]
		
		# 11 digit phone number.
		
		if len(str(did_n)) == 10:
			formatted += "\t1%s => {\n" % (did_n,)
		else:
			formatted += "\t%s => {\n" % (did_n,)
		
		if record:
			formatted += "\t\tMonitor(wav,/srv/pbx/${CDR(accountcode)}/${CDR(uniqueid)},m);\n"
		
		# Construct dial command
		# Get any extra numbers to call.
		c = conn.cursor()
		c.execute("""SELECT remote_ani FROM t_simultaneous_ring WHERE did=%s;""",(did_n,))
		r_ani = c.fetchall()
		del c
		
		# Get the outbound channels to try.
		c = conn.cursor()
		c.execute("""SELECT name FROM v_did_outbound WHERE did = %s;""",(did_n,))
		channels = c.fetchall()
		del c
		
		
		chan_str_a = ["SIP/ATA-%s-L%s" % (did[1],did[2])]
		
		for ani in r_ani:
			for chan in channels:
				chan_str_a.append("SIP/1{0}@{1}".format(ani[0],chan[0]))
		
		chan_str = "&".join(chan_str_a)
		
		formatted += "\t\tDial(%s,%s,r);\n" % (chan_str,ring_sec)
		
		# Voicemail.
		if mailbox:
			formatted += "\t\tVoicemail(%s@default);\n" % (str(mailbox),)
		
		formatted += "\t};\n"
	formatted += "};\n\n"
	
	# Inbound calls from external sources, like Shaw or MTS.
	formatted += "context inbound {\n"
	
	for did in dids:
		did_n = did[0]
		
		if len(str(did_n)) == 10:
			formatted += "\t1%s => {\n" % (did_n,)
		else:
			formatted += "\t%s => {\n" % (did_n,)
		
		# Remove CID Blocking.
		formatted += '\t\tSet(CALLERPRES()=allowed);\n'
		formatted += '\t\tswitch ("${CALLERID(name)}") {\n'
		formatted += '\t\t\tcase "Anonymous":\n'
		formatted += '\t\t\tcase "":\n'
		formatted += '\t\t\tcase "Private":\n'
		formatted += '\t\t\t\tCALLERID(name)="Name Screened";\n'
		formatted += '\t\t\tdefault:\n'
		formatted += '\t\t\t\tbreak;\n'
		formatted += '\t\t};\n'
		
		# Jump to the correct internal line.
		formatted += '\t\tjump ${EXTEN}@internal;\n'
		
		formatted += "\t};\n"
	formatted += "};\n\n"
	
	# Phone context.
	for did in dids:
		did_n = did[0]
		record = did[5]
		mailbox = did[4]
		
		# Include the various contexts this phone can call.
		formatted += "context %s_phone {\n" % (str(did_n),)
		formatted += "\tincludes {\n"
		formatted += "\t\tinternal;\n"
		formatted += "\t\t%s_external;\n" % (str(did_n),)
		formatted += "\t\tinbound;\n"
		formatted += "\t};\n"
		
		# Include a custom *98 that bypasses mailbox # entry and password entry.
		if mailbox:
			formatted += "\t*98 => {\n"
			formatted += "\t\tVoiceMailMain(s%s@default);\n" % (str(mailbox),)
			formatted += "\t};\n"
		
		formatted += "};\n\n"
		
		# External dialing context, needs to be different for each phone so that we can bill appropriately.
		formatted += "context %s_external {\n" % (str(did_n),)
		
		# 7 digit dialing
		formatted += '\t_NXXXXXX => {\n'
		formatted += '\t\tjump 1204${EXTEN};\n'
		formatted += '\t};\n'
		
		# 10 digit dialing
		formatted += '\t_NXXNXXXXXX => {\n'
		formatted += '\t\tjump 1${EXTEN};\n'
		formatted += '\t};\n'
		
		# 11 digit dialing... only allow north america (1 prefix)
		formatted += '\t_1NXXNXXXXXX => {\n'
		
		# If recording is enabled.
		if record:
			formatted += '\t\tMonitor(wav,/srv/pbx/${CDR(accountcode)}/${CDR(uniqueid)},m);\n'
		
		# Get the outbound channels to try.
		c = conn.cursor()
		c.execute("""SELECT name FROM v_did_outbound WHERE did = %s;""",(did_n,))
		channels = c.fetchall()
		del c
		
		chan_str_a = []
		for chan in channels:
			chan_str_a.append("SIP/${EXTEN}@"+chan[0])
		chan_str = "&".join(chan_str_a)
		formatted += '\t\tDial(%s,120);\n' % (chan_str,)
		
		formatted += '\t\tCongestion(30);\n'
		formatted += '\t\tHangup();\n'
		formatted += '\t};\n'
		
		formatted += "};\n\n"
	
	f = open('/etc/ude/switch/extensions.gen.ael', 'w+')
	f.write(formatted)
	f.close()

























































